package com.ambulance.project.biz.controller.agora;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ambulance.framework.web.domain.AjaxResult;
import com.ambulance.framework.web.domain.AjaxResultData;
import com.ambulance.utils.OkHttp3Util;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @Author RXL
 * @Date 2020/7/10 14:34
 * @Version 1.0
 */
@Api(tags = {"声网-业务接口"})
@RestController
@RequestMapping(value = "/agora/v2/biz/")
public class AgoraBizController {

    @Value(("${agora.API.baseurl}"))
    private String baseUrl;

    @Value(("${agora.appId}"))
    private String appid;

    @Value(("${agora.customerId}"))
    private String customerId;

    @Value(("${agora.customerCertificate}"))
    private String customerCertificate;

    @Value(("${agora.API.allOnlineCannel}"))
    private String allOnlineCannel;

    private String acquireUrl = baseUrl + "/v1/apps/" + appid + "/cloud_recording/acquire";

    @Autowired
    private OkHttp3Util okHttp3Util;

    @GetMapping(value = "/OnlineChannel")
    @ResponseBody
    @ApiOperation(value = "获取声网在线频道", notes = "channel", produces = "application/json")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResultData.class, message = "响应")

    })
    public AjaxResult OnlineChannel(
    ) {
        String url = baseUrl + allOnlineCannel + appid;
        final HashMap<String, String> map = Maps.newHashMap();
        final Object o = okHttp3Util.getwithHeader(url, map, getAuthor());
        final JSONObject jsonObject = JSON.parseObject(o.toString());
        final String data = jsonObject.getString("data");
        final JSONObject jsonObject1 = JSON.parseObject(data);
        final JSONArray channels = jsonObject1.getJSONArray("channels");
        return AjaxResult.success(channels);
    }


    @GetMapping(value = "/test")
    @ResponseBody
    @ApiOperation(value = "测试", notes = "channel", produces = "application/json")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResultData.class, message = "响应")

    })
    public AjaxResult test(

    ) {
        // 获取录制资源  /v1/apps/{appid}/cloud_recording/acquire
        // 需要录制的房间号码
        String cname = "39";
        final HashMap<String, Object> map = Maps.newHashMap();
        map.put("cname", cname);
        map.put("uid", "999999999");
        final HashMap<String, Object> map1 = Maps.newHashMap();
        map1.put("resourceExpiredHour", 72);
        map.put("clientRequest", map1);
        final String jsonString = JSON.toJSONString(map);
        final Object o = okHttp3Util.postJsonParamsWithHeader(acquireUrl, jsonString, getAuthor());
        // 获取到资源id
        final JSONObject jsonObject = JSON.parseObject(o.toString());
        final String resourceId = jsonObject.getString("resourceId");


        System.out.println("-----------接口结果START-----------");
        System.out.println(jsonObject);
        System.out.println("-----------接口结果END-----------");
//        final JSONObject jsonObject = JSON.parseObject(o.toString());
//        final String data = jsonObject.getString("data");
//        final JSONObject jsonObject1 = JSON.parseObject(data);
//        final JSONArray channels = jsonObject1.getJSONArray("channels");
        return AjaxResult.success(o);
    }

    private Object startRecordVideo(String cname, String uid, String resourceId, String mode) {
        // 地址格式
        // /v1/apps/{appid}/cloud_recording/resourceid/{resourceid}/mode/{mode}/start
        String recordUrl = baseUrl + "/v1/apps/" + appid + "/cloud_recording/resourceid/" + resourceId + "/mode/" + mode + "/start";
        final HashMap<String, Object> map = Maps.newHashMap();
        map.put("cname", cname);
        map.put("uid", uid);
        final HashMap<String, Object> clientRequest = Maps.newHashMap();
        clientRequest.put("token", "");
        // 订阅设置
        final HashMap<String, Object> recordingConfig = Maps.newHashMap();
        // 0:通信场景 1:直播场景
        recordingConfig.put("channelType", 1);
        // 最长空闲频道时间，单位为秒。如果频道内无用户的状态持续超过该时间，录制程序会自动退出。
        // 该值需大于等于 5，且小于等于 (2的32次方-1)。退出后，再次调用 start 请求，会产生新的录制文件。
        recordingConfig.put("maxIdleTime", 30);
        clientRequest.put("recordingConfig", JSON.toJSON(recordingConfig));

        // storageConfig  	第三方云存储的设置。
        final HashMap<String, Object> storageConfig = Maps.newHashMap();
        //0：七牛云   1：Amazon S3
        //2：阿里云   3：腾讯云   4：金山云
        storageConfig.put("vendor", 1);
        // 第三方云存储指定的地区信息
        storageConfig.put("region", 1);
        // 第三方云存储的 bucket。
        storageConfig.put("bucket", "");
        //第三方云存储的 access key。建议提供只写权限的访问密钥
        storageConfig.put("accessKey", "");
        // 第三方云存储的 secret key。
        storageConfig.put("secretKey", "");
        clientRequest.put("storageConfig", JSON.toJSON(storageConfig));
        map.put("clientRequest", clientRequest);
        return okHttp3Util.postJsonParamsWithHeader(recordUrl, JSON.toJSONString(map), getAuthor());

    }


    private String getAuthor() {
        // 填入 Customer ID 和 Customer Certificate，计算 plainCredentials。
        String plainCredentials = customerId + ":" + customerCertificate;
        // 填入 plainCredentials（使用 Base64 算法编码的 Credential），计算 base64Credentials，即你要的 Authorization 字段。
        return new String(Base64.encodeBase64(plainCredentials.getBytes()));
    }
}
